package youkeda;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class FileUploadThreadServer {
    public static void main(String[] args) throws IOException {


        ServerSocket serverSocket = new ServerSocket(8888);
        //得到接收信息

        //阻塞式等待
        while (true){
            Socket accept = serverSocket.accept();

            //多线程工作，每当有一个发过来就开启一个线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //子类重写run方法的时候不能直接抛出异常那么就trycatch出来
                    try {
                        InputStream inputStream = accept.getInputStream();
                        System.out.println("连接建立");
                        File file = new File("C:\\Users\\鱼尾\\Desktop\\socketChattingRoomSimple\\files");
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        String filename="小余文件"+System.currentTimeMillis()+new Random().nextInt(99999)+".png";
                        // FileOutputStream fileOutputStream = new FileOutputStream(file + "\\1.txt");
                        //名称不用写死
                        FileOutputStream fileOutputStream = new FileOutputStream(file + "\\"+filename);
                        //将得到的信息传入文件夹的指定位置
                        while ((len = inputStream.read(bytes)) != -1) {
                            fileOutputStream.write(bytes, 0, len);
                        }
                        //返回给客户端信息
                        accept.getOutputStream().write("已经成功收到".getBytes());

                        inputStream.close();
                        fileOutputStream.close();
                    }catch (IOException e){
                        System.out.println(e);
                    }
                }
            }).start();
        }




       // serverSocket.close();

    }
}
